package com.test.fundible.fundible_06_loan_apply;

import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.test.fundible.OnOldUserChooseDayListener;
import com.test.fundible.R;
import com.test.fundible.fundible_00_customer_service.Customer_fundibleServiceDialog;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_04_home.MainAct_fundibleivity;

import java.util.ArrayList;

public class LoanApplyActivity_OldUser extends AppCompatActivity {

    private TextView amountTitleTv;
    private TextView loanAmountTv;
    private SeekBar amountSb;
    private View minAndMaxAmountView;
    private TextView minAmountTv,maxAmountTv;
    private LinearLayout itemGroupLayout;

    private LoanDayChooseViewAdapter dayChooseViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fundible_loan_apply_old_user);
        //tag2024
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        SwipeRefreshLayout refreshLayout = findViewById(R.id.aflaou_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            refreshLayout.setRefreshing(false);
            OkHttpUtil.getInstance_fundible().uploadEventPoint("APPLY_2","REFRESH_PULL","");
            startLoading(this,getString(R.string.calculating));
            OkHttpUtil.getInstance_fundible().fetchLnAplDetail_OldUser(this::refreshLoanApplyDetail);
        });

        findViewById(R.id.aflaou_ib_back).setOnClickListener(v -> onBackPressed());
        findViewById(R.id.aflaou_ib_customerservice).setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("APPLY_2","CUSTOMER_SERVICE_CLICK","");
            new Customer_fundibleServiceDialog(this).show();
        });

        amountTitleTv = findViewById(R.id.aflaou_tv_amount_title);
        loanAmountTv = findViewById(R.id.aflaou_tv_loanamount);
        amountSb = findViewById(R.id.aflaou_sb_amount);
        minAndMaxAmountView = findViewById(R.id.aflaou_view_minandmaxamount);
        minAmountTv = findViewById(R.id.aflaou_tv_minamount);
        maxAmountTv = findViewById(R.id.aflaou_tv_maxamount);
        RecyclerView termRv = findViewById(R.id.aflaou_rv_term);
        itemGroupLayout = findViewById(R.id.aflaou_layout_itemgroup);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);//网格布局管理器
        gridLayoutManager.setOrientation(RecyclerView.VERTICAL);
        termRv.setLayoutManager(gridLayoutManager);
        dayChooseViewAdapter = new LoanDayChooseViewAdapter(chooseDay -> {
            startLoading(this,getString(R.string.calculating));
            OkHttpUtil.getInstance_fundible().uploadEventPoint("APPLY_2","DAY_CHOOSE_CLICK",String.valueOf(chooseDay));
            int maxAmount = LoanApplyDetail_OldUser.getInstance_fundible().getMaxAmountNum();
            int minAmount = LoanApplyDetail_OldUser.getInstance_fundible().getMinAmountNum();
            int granularity = LoanApplyDetail_OldUser.getInstance_fundible().getGranularityNum();
            String chooseAmount = String.valueOf(amountSb.getProgress()*granularity);
            OkHttpUtil.getInstance_fundible().fetchLnAplDetail_OldUser(
                    String.valueOf(maxAmount),
                    String.valueOf(minAmount),
                    chooseAmount,
                    String.valueOf(chooseDay), //天数
                    this::refreshLoanApplyDetail
            );

        });
        termRv.setAdapter(dayChooseViewAdapter);

        findViewById(R.id.aflaou_btn_apply).setOnClickListener(v -> {
            startLoading(this,"");
            OkHttpUtil.getInstance_fundible().uploadEventPoint("APPLY_2","SUBMIT_CLICK","");

            int amount = LoanApplyDetail_OldUser.getInstance_fundible().getAmount();
            if (amount<=0){
                Toast.makeText(this,getString(R.string.tips_apply_no_amount_tips),Toast.LENGTH_SHORT).show();
                return;
            }

            OkHttpUtil.getInstance_fundible().aplyLn_OldUser(
                    String.valueOf(amount),
                    String.valueOf(dayChooseViewAdapter.getChooseDay()),
                    this::onLnAplyResp_fundible);
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        startLoading(this,getString(R.string.calculating));
        OkHttpUtil.getInstance_fundible().uploadEventPoint("APPLY_2","START","");
        OkHttpUtil.getInstance_fundible().fetchLnAplDetail_OldUser(this::refreshLoanApplyDetail);
    }

    @SuppressLint("SetTextI18n")
    public void refreshLoanApplyDetail(){

        stopLoading();

        int amount = LoanApplyDetail_OldUser.getInstance_fundible().getAmount();
        boolean canChooseAmount = LoanApplyDetail_OldUser.getInstance_fundible().getChooseAmountFlag();
        int maxAmount = LoanApplyDetail_OldUser.getInstance_fundible().getMaxAmountNum();
        int minAmount = LoanApplyDetail_OldUser.getInstance_fundible().getMinAmountNum();
        int granularity = LoanApplyDetail_OldUser.getInstance_fundible().getGranularityNum();
        int[] dayArr = LoanApplyDetail_OldUser.getInstance_fundible().getDaysArray();

        //显示额度
        loanAmountTv.setText(LoanApplyDetail_OldUser.getInstance_fundible().getAmountWithCurrency());
        //显示天数
        dayChooseViewAdapter.setDays(dayArr);
        dayChooseViewAdapter.setChooseDay(LoanApplyDetail_OldUser.getInstance_fundible().getDays());
        //是否可选金额
        if (canChooseAmount){
            amountTitleTv.setText(getString(R.string.apply_old_user_choose_loan_amount));
            amountSb.setVisibility(View.VISIBLE);
            minAndMaxAmountView.setVisibility(View.VISIBLE);

            //刷新额度选择控件
            amountSb.setMax(maxAmount/granularity);
            amountSb.setMin(minAmount/granularity);
            amountSb.setProgress(amount/granularity);
            minAmountTv.setText(String.valueOf(minAmount));
            maxAmountTv.setText(String.valueOf(maxAmount));
            amountSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    loanAmountTv.setText(String.valueOf(progress*granularity));
                }
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    startLoading(LoanApplyActivity_OldUser.this,getString(R.string.calculating));
                    String chooseAmount = String.valueOf(seekBar.getProgress()*granularity);
                    OkHttpUtil.getInstance_fundible().uploadEventPoint("APPLY_2","AMOUNT_CHOOSE",chooseAmount);
                    OkHttpUtil.getInstance_fundible().fetchLnAplDetail_OldUser(
                            String.valueOf(maxAmount),
                            String.valueOf(minAmount),
                            chooseAmount,
                            String.valueOf(dayChooseViewAdapter.getChooseDay()), //天数
                            () -> refreshLoanApplyDetail()
                    );
                }
            });

        }else {
            amountTitleTv.setText(getString(R.string.loan_amount));
            amountSb.setVisibility(View.GONE);
            minAndMaxAmountView.setVisibility(View.GONE);
        }


        refreshParamView_fundible();
    }

    @SuppressLint("InflateParams")
    private void refreshParamView_fundible(){

        itemGroupLayout.removeAllViews();

        ArrayList<LnoaAp_fundiblel_fundibleyItem> params = LoanApplyDetail_OldUser.getInstance_fundible().getDetailItemList_fundible();
        View groupView = null;
        LinearLayout groupLayout = null;

        for (LnoaAp_fundiblel_fundibleyItem lnAplyItem:params){

            if (lnAplyItem.isTitle_fundible()){
                if (groupView!=null && groupLayout!=null) itemGroupLayout.addView(groupView);
                groupView = LayoutInflater.from(this).inflate(R.layout.view_fundible_item_bg_fundible_group,null);
                groupLayout = groupView.findViewById(R.id.vibg_layout_group);
                addItem(groupLayout,lnAplyItem);
            }else {
                if (groupView!=null && groupLayout!=null) addItem(groupLayout,lnAplyItem);
            }

        }

        itemGroupLayout.addView(groupView);

    }

    private void addItem(LinearLayout group, LnoaAp_fundiblel_fundibleyItem lnAplyItem){

        @SuppressLint("InflateParams") View item = LayoutInflater.from(this).inflate(R.layout.item_fundible_lnaply_detail,null);

        TextView nameTv = item.findViewById(R.id.ilda_tv_name);
        TextView valueTv = item.findViewById(R.id.ilda_tv_value);

        nameTv.setText(lnAplyItem.getShowName_fundible());
        valueTv.setText(lnAplyItem.getShowDetail_fundible());

        if (lnAplyItem.isTitle_fundible()){
            nameTv.setTextColor(Color.parseColor("#FF212321"));
            nameTv.setTypeface(Typeface.DEFAULT_BOLD);
            valueTv.setTextColor(Color.parseColor("#FF1E492E"));
            valueTv.setTypeface(Typeface.DEFAULT_BOLD);
        }

        group.addView(item);
    }

    public void onLnAplyResp_fundible(){
        OkHttpUtil.getInstance_fundible().requestUsPrcs(this::onProcessResp_fundible);
    }

    public void onProcessResp_fundible(){
        stopLoading();
        Intent intent = new Intent(this, MainAct_fundibleivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("APPLY_2","END","");
    }

}